<?php
include(BASE_URL.'includes/admin/editors/fckeditor/fckeditor.php');
if($_GET['serialize']) {
	foreach($_POST['order'] as $key => $value) {
		$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET orderingid = '{$key}' WHERE id = '{$value}' LIMIT 1";
		$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', mysql_error()));
	}
	echo $admin->message('success', 'Success! The page order was updated at '.date('g:i:s').'!', 'However, if there are red boxes above this one, the reordering process didn\'t work.');
	exit();
}
$id = mysql_real_escape_string($_GET['id']);
if($_POST['deleteid']) {
	$did = $_POST['deleteid'];
	$did = explode('-', $did);
	$did_cat = $did[0];
	$id = $did[1];
	$sql = "DELETE FROM ".DBTABLEPREFIX."content_pages WHERE id = '{$id}' LIMIT 1";
	$query = $admin->db_query($sql) or die($admin->message('error', 'MySQL Error', mysql_error()));
	if(!$query) {
		echo $admin->message('error', 'Unknown Error', 'See above.');
	}
	else {
		echo $admin->message('success', 'Page Deleted', "Let's hope that wasn't an accident!");
	}
	exit();
}
if($_POST['save']) {
	$list = $theme->buildNavArray();
	$secondary_list = $theme->arraySecondaryNavigation();
	foreach($_POST as $key => $value) {
		$_POST[$key] = mysql_real_escape_string($value);
	}
	$error = "";
	if($_POST['page-title'] == "") {
		$error[] = "Don't leave the page title blank!";
	}
	if($_POST['menu-title'] == "") {
		$error[] = "Don't leave the menu title blank!";
	}
	$time = time();
	if($error == "") {
		$parent = explode('-', $_POST['parent-item']);
		$parent_cat = $parent[0];
		$parent_id = $parent[1];
		if($parent_cat == "p") {
			$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET title = '".$_POST['page-title']."', content = '".$_POST['content']."', menutitle = '".$_POST['menu-title']."',
			parent_id = '".$parent_id."', orderingid = '".$_POST['weight']."', time = '$time', secondary = '' WHERE id = '$id'";
		}
		elseif ($parent_cat == "s") {
			$sql = "UPDATE ".DBTABLEPREFIX."content_pages SET title = '".$_POST['page-title']."', content = '".$_POST['content']."', menutitle = '".$_POST['menu-title']."',
			parent_id = '".$parent_id."', orderingid = '".$_POST['weight']."', time = '$time', secondary = 'yes' WHERE id = '$id'";
		}
		$content = $admin->db_query($sql) or die(mysql_error());
		if($content) {
			$output .= $admin->message("success","Woohoo! Your Page \"".stripslashes(stripslashes(stripslashes($_POST['page-title'])))."\" was updated!", "It will show up as \"".stripslashes(stripslashes(stripslashes($_POST['menu-title'])))."\" in the menu.");
		}
	}
	if($error !== "") {
		$list_errors = "<ul class='error-list'>";
		foreach($error as $key => $value) {
			$list_errors .= "<li>".$value."</li>";
		}
		$list_errors .= "</ul></div>";
		$output .= $admin->message("error", "Oops! We encountered ".count($error)." error(s) when trying to add the page.", $list_errors);
	}
	$options = "<option value='0'>None (Root Item)</option>";
	$list = $theme->buildNavArray();
	for($col = -20; $col <= 20; $col++) {
		$weight .= "\t<option value='$col'";
		if($col == $_POST['weight']) {
			$weight .= " selected='selected'";
		}
		$weight .= ">$col</option>\n";
	}
	
	$FCKeditor_content = new FCKeditor('content') ;
	$FCKeditor_content->BasePath = THEME_URL."includes/admin/editors/fckeditor/";
	$FCKeditor_content->Value = stripslashes(stripslashes(stripslashes($_POST['content'])));
	$FCKeditor_content->Width = '100%' ;
	$FCKeditor_content->Height = '350' ;
	$FCKeditor_content_html = $FCKeditor_content->CreateHtml();

$form = '
						<form action="" method="post" class="niceform">
							<fieldset>
								<h2>Edit Page "'.stripslashes(stripslashes(stripslashes($_POST['page-title']))).'"</h2>
								<div class="form-row">
									<label for="page-title" class="page-title">Page Title:</label><span><input type="text" class="page-title" name="page-title" value="'.stripslashes(stripslashes(stripslashes($_POST['page-title']))).'" /></span>
								</div>
								<div class="form-row">
									<label for="menu-title">Menu Title:<span class="small gray">This is what will show up in the menu.</span></label><span><input type="text" name="menu-title" value="'.stripslashes(stripslashes(stripslashes($_POST['menu-title']))).'" /></span>
								</div>
								<div class="form-row">
									<label for="parent-item">Parent Item</label>
									<span>
										<select name="parent-item">
											<optgroup label="Main Menu">
												<option value="p-0">None (Root Item)</option>
												'.$theme->optionListFromArray($list, "p-", $parent_id).'
											</optgroup>
											<optgroup label="Secondary Optional Menu">
												<option value="s-0">None (Root Item)</option>
												'.$theme->optionListFromArray($secondary_list, "s-", $parent_id).'
											</optgroup>
										</select>
									</select>
									</span>
								</div>
									<div class="form-row">
										<label for="weight">Weight <a href="javascript:;" class="helplink" title="<strong style=\'font-size:16px;display:block;\'>Weight</strong>Weight Allows you to manage how items are ordered.<br />For example: If you weight this page 12 and another page 11, in the menu the other page would show before this one.">[Help]</a></label>
										<span>
											<select name="weight">
											'.$weight.'
											</select>
										</span>
									</div>
								<div class="form-row">
									<label class="content" for="content">Content</label>
									<span class="content">
										'.stripslashes(stripslashes(stripslashes($FCKeditor_content_html))).'
									</span>
								</div>
								<div class="form-row form-row-last">
									<label for="save">Save</label>
									<span><input type="submit" name="save" value="Update Page" class="submit" /></span>
								</div>
							</fieldset>
						</form>
	';
	$output .= $form;
}
elseif (isset($_GET['id'])) {
	$list = $theme->buildNavArray();
	$secondary_list = $theme->arraySecondaryNavigation();
	$list = $theme->buildNavArray();
	$sql = "SELECT * FROM ".DBTABLEPREFIX."content_pages WHERE id = $id LIMIT 1";
	$content = $admin->db_query($sql) or die(mysql_error());
	$count = mysql_num_rows($content);
	if($count == "1") {
		$row = mysql_fetch_array($content);
			for($col = -20; $col <= 20; $col++) {
				$weight .= "\t<option value='$col'";
				if($col == $row['orderingid']) {
					$weight .= " selected='selected'";
				}
				$weight .= ">$col</option>\n";
			}
			foreach($row as $key => $value) {
				$row[$key] = stripslashes(stripslashes(stripslashes($value)));
			}
			$FCKeditor_content = new FCKeditor('content') ;
			$FCKeditor_content->BasePath = THEME_URL.'includes/admin/editors/fckeditor/';
			$FCKeditor_content->Value = stripslashes(stripslashes(stripslashes($row['content'])));
			$FCKeditor_content->Width = '100%' ;
			$FCKeditor_content->Height = '350' ;
			$FCKeditor_content_html = $FCKeditor_content->CreateHtml();
			$main = $theme->optionListFromArray($list, "p-", $row['parent_id']);
			$seco = $theme->optionListFromArray($secondary_list, "s-", $row['parent_id']);
			if($row['secondary'] == 'yes') {
				if(substr_count('selected=', $seco) > 0) {
					$seco = '<option value="s-0">None (Root Item)</option>'.$seco;
				}
				else {
					$seco = '<option value="s-0" selected="selected">None (Secondary Menu Root Item)</option>'.$seco;
				}
			}
			else {
				if(substr_count('selected=', $main) > 0) {
					$main = '<option value="p-0">None (Root Item)</option>'.$main;
				}
				else {
					$main = '<option value="p-0" selected="selected">None (Main Menu Root Item)</option>'.$main;
				}
			}
		$form = '
							<form action="" method="post">
								<fieldset>
									<h2>Edit Page "'.$row['title'].'"</h2>
									<div class="form-row">
										<label for="page-title" class="page-title">Page Title:</label><span><input type="text" class="page-title" name="page-title" value="'.$row['title'].'" /></span>
									</div>
									<div class="form-row">
										<label for="menu-title">Menu Title:<span class="small gray">This is what will show up in the menu.</span></label><span><input type="text" name="menu-title" value="'.$row['menutitle'].'" /></span>
									</div>
									<div class="form-row">
										<label for="parent-item">Parent Item</label>
										<span>
											<select name="parent-item">
												<optgroup label="Main Menu">
													'.$main.'
												</optgroup>
												<optgroup label="Secondary Optional Menu">
													'.$seco.'
												</optgroup>
											</select>
										</select>
										</span>
									</div>
									<div class="form-row">
										<label for="weight">Weight <a href="javascript:;" class="helplink" title="<strong style=\'font-size:16px;display:block;\'>Weight</strong>Weight Allows you to manage how items are ordered.<br />For example: If you weight this page 12 and another page 11, in the menu the other page would show before this one.">[Help]</a></label>
										<span>
											<select name="weight">
											'.$weight.'
											</select>
										</span>
									</div>
									<div class="form-row">
										<label class="content" for="content">Content</label>
										<span class="content">
											'.$FCKeditor_content_html.'
										</span>
									</div>
									<div class="form-row form-row-last">
										<label for="save">Save</label>
										<span><input type="submit" name="save" value="Update Page" class="submit" /></span>
									</div>
								</fieldset>
							</form>
		';
	}
	else {
		
	}
	$output .= $form;
}
else {
	$after = '	</fieldset></form>';
	$output .= "
	<script type='text/javascript' src='".THEME_URL."includes/admin/js/jquery-ui-sortable-1.6rc4.packed.js'></script>
	<script type='text/javascript'>
	$(document).ready(function() {
		$('#rearrangeButton').toggle(function () {
			$('#list-pages > li >.rearrange-page').css('visibility','visible');
			$('#list-pages').sortable({
				axis: 'y'
			});
			$(this).text('Save');
		},function () {
			$('#list-pages > li >.rearrange-page').css('visibility','hidden');
			var serial = serializeArray($('.primary-list-pages').sortable('toArray'));
			$('#list-pages').sortable('destroy');
			$.ajax({
				type: 'POST',
				url: '?page=edit-and-delete-pages&serialize=true',
				data: serial,
				success: function(responseText) {
					$('.response').html(responseText);
					addClose();
			}
			});
			$(this).text('Rearrange Pages');
		});	
		$('#secondaryRearrangeButton').toggle(function () {
			$('#list-pages2 > li > .rearrange-page').css('visibility','visible');
			$('#list-pages2').sortable({
				axis: 'y'
			});
			$(this).text('Save');
		},function () {
			$('#list-pages2 > li >.rearrange-page').css('visibility','hidden');
			var serial = serializeArray($('#list-pages2').sortable('toArray'));
			$('#list-pages2').sortable('destroy');
			$.ajax({
				type: 'POST',
				url: '?page=edit-and-delete-pages&serialize=true',
				data: serial,
				success: function(responseText) {
					$('.response').html(responseText);
					addClose();
			}
			});
			$(this).text('Rearrange Pages');
		});	
		$('.secondary-list-pages .admin-edit-link').each(function () {
			var id = $(this).attr('id');
			$(this).attr('id', 's-'+id);
		});
	});
	</script>
	<form action='' method='get'>
	<fieldset>
		<h2>Edit, Delete and Rearrange Pages</h2>
		<p><strong>To delete a page:</strong> click the red 'X' to the far left of the page you wish to delete.</p>
		<p><strong>To edit a page:</strong> click the white sheet of paper to the far left of the page you wish to edit. Alternativly, you can click on name of the page</p>
		<p><strong>To rearrange pages:</strong> click the Rearrange button to the far right and then click and drag items into place. PLEASE NOTE: At this time you can only arrange top level items.</p>
	<br />
	<div class='response'></div>
	<div class='right disable-warning'><button class='button' id='rearrangeButton'>Rearrange Main Pages</button></div>
	<h3>Main Menu Items</h3>
	<div class='left disable-warnings' style='top:0;margin-bottom:10px;padding-left:59px;'>If a parent item is deleted, <strong>ALL SUB-PAGES WILL BE DELETED!</strong></div>\n".
	$admin->adminPublicPageList("list-pages' class='primary-list-pages", "list-page-sub", "selected", true, "edit-and-delete-pages", false, $theme->arrayNavigation()).
	"<div class='right disable-warning'><button class='button' id='secondaryRearrangeButton'>Rearrange Secondary Pages</button></div>".
	'<br /><h3>Secondary Menu Items</h3>'.
	$admin->adminPublicPageList("list-pages2' class='secondary-list-pages", "list-page-sub", "selected", true, "edit-and-delete-pages", false, $theme->arraySecondaryNavigation());
}
$admin->page_info['content']['page_title'] = "Edit a Page";
$admin->page_info['content']['page_content']	= $output.$after;
//Display page
include(BASE_URL.'includes/admin/admin.php');
?>